/**
 * 
 */
    
    var selectItem;
    var gridItem;
    var card;
    var isPushCard;
    var totalAmount=0;
    var needToPay=0;
    
    var cardList=new Array();
    var rechargeCard=new Array();
    var order_detail=new Array();
    var order_payment=new Array();
    var productNeedRegist=new Array(); 
    
    
    var sum=0;
	var needPay=0;
    
	var real_name;
	var uphone;
	var umember_number;
	
	
	var zhekou=0; //折扣
	var dikou=0; //抵扣
	var sjzf=0;  //实际支付
	 $(document).ready(function() {
    	kendo.culture("zh-CN");
    	
        	$("#toolbar").kendoToolBar({
	            resizable: false,
	            items: [
	                //{ type: "button", text: "九宫格",click: addItems2 },
	                { template:'<button  onclick="addItems2()" class="tools_button">九宫格</button>'},
	                { template:'<button  onclick="addItems()" class="tools_button">添加商品</button>'},

	                { type: "separator" },
	                { type: "separator" },
	                { template: "<label>手机号</label><input name='phone' value='' id='phone' class='k-textbox'>" },
	                { template: "<label>卡号</label><input name='cardNumber' value='' id='cardNumber' class='k-textbox'>" },
	                
	                { template:'<button  onclick="pushCard()" class="tools_button">查询</button>'}
	                
	             //   { type: "button", text: "查询",click: pushCard }
	            ]
	        });

          $("#phone").keydown(function(event){
      		var e = event || window.event || arguments.callee.caller.arguments[0]; 
    		if(e.keyCode==13){
    			pushCard();
    		}
          });
          
          $("#cardNumber").keydown(function(event){
        		var e = event || window.event || arguments.callee.caller.arguments[0]; 
      		if(e.keyCode==13){
      			pushCard();
      		}
            });
          
            $("#phone").blur(function(){
            	pushCard();
          });
            $("#cardNumber").blur(function(){
            	pushCard();
          });


            dataSource = new kendo.data.DataSource({
               transport: {
                    read:  {
                        dataType: "jsonp",
                        data:[]
                    }
                },

                serverFiltering: true,
                schema: {
               		model: {
				        fields: {
				          code:{editable: false},
				          name:{editable: false},
				          unit_price:{editable: false},
				          business_type_code:{editable: false},
				          unit_price:{editable: false},
				          amount:{editable: false},
				          quantity:{editable: false},
				          member_card:{defaultValue:{member_number:""}},
				        }
				    }
                }
            });
            
            dataSourcecard = new kendo.data.DataSource({
               transport: {
                    read:  {
                        dataType: "jsonp",
                        data:[]
                    }
                },
                serverFiltering: true,
                schema: {           		
               		model: {
				        fields: {
				          member_number:{editable: false},
				          business_type: {editable: false},
				          name: {editable: false},
				          remain_quantity: {editable: false},
				          unit: {editable: false}
				        }
				    }
                }
            });
            $("#cardContent").kendoGrid({
                dataSource: dataSourcecard,
                selectable: "multiple row",
                allowCopy: true,
            	editable:'incell',
            	columns: [
                	//{ field:"id", template: "<input type='checkbox' id='#:id#' />",width: "120px",headerTemplate: '<input type="checkbox" id="check-all" />'},
                   	{ field:"member_number", title: "合同号",width: "120px",editable: false},
                   	{ field:"business_type", title: "业务类型",width: "120px",editable: false},
                   	{ field:"name", title: "产品名称",width: "120px",editable: false},                   	
            		{ field:"remain_quantity", title: "剩余数量",width: "80px",editable: false},
            		{ field:"unit", title: "单位",width: "60px",editable: false}
            	]
            });
            
            $("#cardContent").on("dblclick", "td", function (e) {
			    var customergrid = $("#cardContent").data("kendoGrid");
	            var data = customergrid.dataItem($(e.currentTarget).closest("tr"));
	            var business_type_code=data.business_type_code;
	            if(business_type_code.substring(0,1)==2){
	            	layIndex = layer.open({
						title:"商品选择",
						type: 2,
						fix: false,
				        //shadeClose: true,
				        maxmin: true,
						area: ['1000px', '525px'], //宽高
					    content: path+"/assist/productList?deptID="+deptID+"&name="+data.name
					});
	            }     
	         
			});
            
			var rechargeCardDataSource = new kendo.data.DataSource({
  				data:[],
                serverFiltering: true,
                schema: {
               		model: {
				        fields: { 
				          recharge_number:{editable: false},
				          card_number:{editable: false},
				          balance: {editable: false},
				          rechargecard_id: {editable: false},
				          discount_rate:{editable: false},
				          rechargeCardCategory2:{editable: false},
				          begin_time: {editable: false}
				        }
				    }
                }
			});
            
            $("#rechargeCard").kendoGrid({
                dataSource: rechargeCardDataSource,
                selectable: "multiple row",
                allowCopy: true,
            	editable:'incell',
            	columns: [
                   	{ field:"recharge_number", title: "合同号",width: "80px",editable: false},
                   	{ field:"balance", title: "余额",width: "60px",editable: false},
                   	{ field:"discount_rate", title: "折扣率",width: "60px",editable: false},
                   	{ field:"rechargeCardCategory2", title: "折扣率",width: "60px",editable: false},                  	
                   	{ field:"rechargecard_id", title: "业务类型",width: "120px",editable: false,hidden: true},                   	
            		{ field:"begin_time", title: "剩余数量",width: "120px",editable: false,hidden: true}
            	]
            });
            
            
            $("#grid").kendoGrid({
                dataSource: dataSource,
                selectable: "multiple row",
                allowCopy: true,
                groupable: {
                    messages: {
                      empty: "将列拖拽到此处进行分类查看"
                    }
                },
                editable:'inline',
                columns: [
                	//{ field:"id", template: "<input type='checkbox' id='#:id#' />",width: "120px",headerTemplate: '<input type="checkbox" id="check-all" />'},
                   	{ field:"code", title: "代码",width: "50px",editable: false},
                   	{ field:"name", title: "商品名",width: "80px",editable: false},
                    { field:"unit_price", title:"单价",  width: "50px",editable: false},
                    { field:"business_type_code", title: "业务代码",width: "60px",editable: false},                                        
                    { field:"amount", title: "金额",width: "60px"},
                    { field:"quantity", title: "数量",width: "40px"},
                    { field:"member_card.member_number", title: "合同号", width: "150px",                    
                         template:function(data){if(data.member_card){
                        	 return data.member_card.member_number;}} ,
	                    editor: function(container, options) {
						     var input = $("<input/>");
						     input.attr("name", options.field);
						     input.appendTo(container);
						     input.kendoComboBox({
						     	dataValueField: "member_number",
						       dataTextField: "member_number",
						       dataSource: {data:cardList},				       
						select :function(e){
						        	var dataItem = e.sender.dataItem(e.item);	
						        	var curGrid = $("#grid").getKendoGrid();
						        	var selGridItem = curGrid.select();
						        	if(selGridItem)
						        	{
						        		var curDataItem = curGrid.dataItem(selGridItem);
						        		if(curDataItem.member_card.member_number!=dataItem.member_number){
						        			var bool=checkGridRight(curDataItem,dataItem.member_number);
						        			if(!bool){
						        				e.preventDefault();
						        			}
						        		}
						        	}
						        }
						     });
						 }},
					{ field:"remark", title: "备注",width: "80px",editable: true},
                    { field:"order_product_id", title: "商品id",width: "150px",hidden: true},
                    { field:"unit_code", title: "单位代码",width: "80px",hidden: true},
                   	{ field:"order_product_kids_park_id", title: "商品详细id",width: "160px",hidden: true},										
                    { command: ["edit","destroy"], title: "操作", width: "100px" }                                       
                    ],
  				dataBound: function(e) {
    				getTotalAmount();
  			},
            });
            
            $("#grid").data("kendoGrid").dataSource.online(false);
            $("#cardselect").kendoComboBox({
    			dataTextField: "member_number",
    			dataValueField: "member_number",
    			dataSource: cardList
			});
                   
            //用来产生商品代码动态查询
            var dataSourceap = new kendo.data.DataSource({
	  			transport: {
	  			  read: {
	  			  //url: spera.spera_consume
	    		  url: spera.spera_consume+"/consumeBackground/getProductList",
	     		  dataType: "jsonp",
	 			  data: function() {
						return {
						     kids_park_id:'04428ed2-a555-11e5-8ece-1051721d3a6c'					     
						 };
						}
	   				 }
	 			 }
			});

		});
		//点击确认
		 var checkc=function(e){
            	alert('checkc');
            	var grid = $("#grid").data("kendoGrid");
				e.preventDefault();
	            var data = grid.dataItem($(e.currentTarget).closest("tr"));
         }
		
		//刷充值卡
		var pushRechargeCard=function(req){
			var grid = $("#rechargeCard").data("kendoGrid");
			var gridData = grid.dataSource.data();			
			
			$("#rechargeCard").data("kendoGrid").dataSource.data([]);
						
            //遍历添加
            $.each(req.rechargeCard, function (i, item) {
            	$("#rechargeCard").data("kendoGrid").dataSource.add(item);
            });
        }
		
		//会员卡
		var pushMemberCard=function(req){
			var grid = $("#cardContent").data("kendoGrid");			 			 
			var gridData = grid.dataSource.data();
            
			$("#cardContent").data("kendoGrid").dataSource.data([]);
			
			card=new Array();
			cardList=new Array();

			//遍历
			$.each(req.memberCard, function (i, item) {
				if(i==0){
					real_name=req.user.real_name;
					uphone=req.user.phone;
					umember_number=req.user.member_number;					
				}				
             		cardList.push(item);
			})			
			//遍历添加
             $.each(req.dataset, function (i, item) {             	
             	$("#cardContent").data("kendoGrid").dataSource.add(item);
             });
           	 $("#cardContent").data("kendoGrid").dataSource.fetch();
           	 card =	$("#cardContent").data("kendoGrid").dataSource.data();
        }
		//刷卡
		
		var isPushingCard=0;
		
		var pushCard=function(e){

			if(isPushingCard==1){
				return false;
			}
			isPushingCard=1;
		
			var cardNumber=$('#cardNumber').val();
			var phone3=$('#phone').val();
			var temp=true;
			$.ajax({
   			 	url: spera.spera_consume+"/consumeBackground/getCardDetail",    //请求的url地址
   			 	dataType: "jsonp",   //返回格式为json
   			 	async: true, //请求是否异步，默认为异步，这也是ajax重要特性
   			 	data: { "card_number": cardNumber,"phone":phone3 },    //参数值
   			 	//type: "jsonp",   //请求方式
   			 	beforeSend: function() {
      			  //请求前的处理
   			 	},
   			 	success: function(req) {
   			 		if(req.status==0){
   			 			alert(req.msg);
   			 			isPushingCard=0;
   			 			return false;
   			 		}

	   			 	if(req.dataset!=''){
	   			 		pushMemberCard(req);
	   			 	}
	   			 	if(req.rechargeCard!=''){
	   			 		pushRechargeCard(req);
	   			 	}
	   			 	
	   			 getTotalAmount();
	   			 isPushingCard=0;
				},
				error:function(req) {
					isPushingCard=0;					
				}
			});
		}
		
		var addItems=function(e){
			layIndex = layer.open({
				title:"商品选择",
				type: 2,
				fix: false,
		        //shadeClose: true,
		        maxmin: true,
		        area: ['1100px', '525px'],
				 //宽高
			    content: path+"/assist/productList?deptID="+deptID,
			});
			
		}
		
		var addItems2=function(e){
			layIndex = layer.open({
				title:"商品选择",
				type: 2,
				fix: false,
		        //shadeClose: true,
		        maxmin: true,//760
		       //  area: ['830px', '715px'],
		        area: ['815px', '510px'],
				 //宽高
			    content: path+"/assist/productList2?deptID="+deptID,
			});
			
		}
		
		
		//添加grid
		var addItem=function(e){
			var selectItemarray=new Object();
			if(selectItem==null){
				alert('所选不能为空');
				return false;
			}
			
			var quantity2=$('#quantity').val();
			if(!(!isNaN(quantity2)&& quantity2%1 === 0&&quantity2>0)){
				alert('请输入正确的数字');
				return false;
			}
			
			selectItemarray.name=selectItem.name;
			selectItemarray.unit_price=selectItem.unitPrice;
			selectItemarray.desc=selectItem.desc;
			selectItemarray.code=selectItem.code;
			selectItemarray.order_product_kids_park_id=selectItem.order_product_kids_prak_id;
			
			selectItemarray.order_product_id=selectItem.order_product_id;
			selectItemarray.business_type_code=selectItem.business_type_code;
			selectItemarray.unit_code=4;		
			selectItemarray.unit='元';
			selectItemarray.quantity=$('#quantity').val();			
			selectItemarray.amount=$('#quantity').val()*selectItem.unitPrice;
			selectItemarray.needpayquantity=$('#quantity').val();			
			selectItemarray.needpayamount=$('#quantity').val()*selectItem.unitPrice;
			selectItemarray.member_card = {member_number:""}; 
			
			var rechargeCard3=$("#rechargeCard").data("kendoGrid").dataSource.data();	
			$.each(rechargeCard3, function (i, item) {
				
				if(item.name==selectItem.name){
					selectItemarray.member_card ={member_number:item.member_number}; 
				}				
			})	
			$("#grid").data("kendoGrid").dataSource.add(selectItemarray);	
			//初始化总金额
			totalAmount=0;
			//修改需要支付的总金额
			getTotalAmount();
		}
		
		//验证grid数字的正确性
		var checkGridRight=function(dataItem,member_number){
			var gdate=$("#grid").data("kendoGrid").dataSource.data();
			var cardContent2=$("#cardContent").data("kendoGrid").dataSource.data();
			var temp2=true;
			var temp=true;
			var cardHasContent=true;
			$.each(gdate, function (i, item) {
				//当选择了卡片时 需要验证卡片剩余内容是否充足
				if(item.member_card.member_number!=""){
					//遍历整个grid找出同一张卡刷的相同产品的数量
					if(dataItem.order_product_id==item.order_product_id&&member_number==item.member_card.member_number){
						temp2=false;
					}
				}
			})
			if(!temp2){
				alert('同一商品一张卡同一个订单只能支付一次');
				return temp2;
			}
					
			//遍历卡内容验证卡是否能够支付
			var hasContent=false;
			$.each(cardContent2, function (i3, item3) {
				if(item3.order_product_id==dataItem.order_product_id&&item3.member_number==member_number){
					hasContent=true;
					if(item3.remain_quantity<dataItem.quantity){
						temp=false;
					}
				}
			});
			if(!hasContent){
				alert('该卡不包含该内容');
				return hasContent;
			}			
			if(!temp){
				alert('卡内容不够支付');
				return temp;
			}
			return true;
		};
		
		//更新总数
		var remainNeedPay=0;
		var noDiscountNeedPay=0;
		var dzhRemainNeedPay=0;
		var getTotalAmount=function(){
			//清空参数
			order_detail=[];
			order_payment=[];
			var gdate=$("#grid").data("kendoGrid").dataSource.data();
			var cardContent2=$("#cardContent").data("kendoGrid").dataSource.data();
			sum=0;
			needPay=0;
			noDiscountNeedPay=0;
			dzhRemainNeedPay=0;
			
			zhekou=0; //折扣
			dikou=0; //抵扣
			sjzf=0;  //实际支付
			
			productNeedRegist=new Array();
			 $.each(gdate, function (i, item) {			 
				 //判断用户
				 if(item.isNeedRegistration=='1'){
 	 
					 var v=new Object();
					 v.quantity =item.quantity;
					 v.order_product_kids_park_id=item.order_product_kids_park_id;
					 v.name=item.name;
				 
					 productNeedRegist.push(v);
				}
				 			 
					//更新总数
                 	sum=item.unit_price*item.needpayquantity+sum;                 
                 	
                 	//需要支付金额
                 	if(item.member_card.member_number==""){
	                 	//	alert('kong');
	                 	if(item.isDiscount){
	                 		needPay=item.unit_price*item.needpayquantity+needPay;
	                 	}else{
	                 		noDiscountNeedPay=item.unit_price*item.needpayquantity+needPay;
	                 	}           	
						var  order_detail_item=new Object; 
						order_detail_item.business_type_code=item.business_type_code;
						order_detail_item.unit_code=item.unit_code;
						order_detail_item.unit=item.unit;
						order_detail_item.name=item.name;
						order_detail_item.amount=item.amount;
						order_detail_item.quantity=item.quantity;
						order_detail_item.order_product_kids_park_id=item.order_product_kids_park_id;

						order_detail_item.unit_price=item.unit_price;
						order_detail_item.amount=item.amount;
						order_detail_item.remark=item.remark;
						order_detail_item.remainQuantity=item.remainQuantity;
						
						
	                 	order_detail.push(order_detail_item);
                 	}else{
                 		//使用会员卡内容支付
                 	var  order_detail_item=new Object; 
                 	$.each(cardContent2, function (i2, item2) {
                 		if(item2.order_product_id==item.order_product_id&&item2.member_number==item.member_card.member_number){
                 			//alert('使用会员卡内容支付');
                 			order_detail_item.business_type_code=item2.business_type_code;
                 			order_detail_item.unit_code=item2.unit_code;
                 			order_detail_item.unit=item2.unit;
                 			order_detail_item.name=item.name;
                 			order_detail_item.quantity=item.quantity;
                 			order_detail_item.membercard_id=item2.membercard_id;
                 			order_detail_item.order_product_kids_park_id=item.order_product_kids_park_id;
                 			order_detail_item.card_number=item2.card_number;
                 			order_detail_item.package_detail_id=item2.package_detail_id;
                 			order_detail_item.card_detail_id=item2.card_detail_id;
                 			
    						order_detail_item.unit_price=item.unit_price;
    						order_detail_item.amount=item.amount;
    						order_detail_item.remainQuantity=item.remainQuantity;
                 			//计算抵扣
    						dikou=dikou+item.unit_price*item.quantity;
    						
                 			order_detail.push(order_detail_item);
                 		};
                 	})
                 	}
                 });
            //处理现金支付
            var rdate=$("#rechargeCard").data("kendoGrid").dataSource.data();
            
          	//按折扣率排序      
			remainNeedPay=needPay;
			noDiscountremainNeedPay=noDiscountNeedPay;
			 $.each(rdate, function (i3, item3) {
				 	if(item3.rechargeCardCategory==1){
			 
					var order_payment_item=new Object; 
			 		order_payment_item.payment_way_code=2;
			 		order_payment_item.payment_way='充值卡';			 		
			 		order_payment_item.card_number=item3.card_number; 
			 		order_payment_item.rechargecard_id=item3.rechargecard_id;			 					 		
			 
			 	if(remainNeedPay>0||noDiscountNeedPay>0){
			 		if(item3.balance>=(remainNeedPay*item3.discount_rate+noDiscountremainNeedPay)){
			 			
			 			order_payment_item.amount=remainNeedPay+noDiscountNeedPay;
				 		order_payment_item.totalAmount=remainNeedPay*item3.discount_rate+noDiscountremainNeedPay;	 		
				 		
				 		zhekou=zhekou+remainNeedPay*(1-item3.discount_rate);
				 		
				 		remainNeedPay=0;
				 		noDiscountremainNeedPay=0;
				 		
				 		
				 	}else if(item3.balance>=remainNeedPay*item3.discount_rate){
			 			order_payment_item.amount=(item3.balance/item3.discount_rate).toFixed(2);
				 		order_payment_item.totalAmount=item3.balance;	 		
				 		
				 		zhekou=zhekou+remainNeedPay*(1-item3.discount_rate);
				 		
				 		remainNeedPay=0;
				 		noDiscountremainNeedPay=remainNeedPay*item3.discount_rate+noDiscountremainNeedPay-item3.balance;
	
				 	}else{
				 		order_payment_item.amount=(item3.balance/item3.discount_rate).toFixed(2);
				 		order_payment_item.totalAmount=item3.balance;				 		
				 		zhekou=zhekou+item3.balance*(1-item3.discount_rate);				 		
				 		remainNeedPay=remainNeedPay-(item3.balance/item3.discount_rate).toFixed(2);				 						 		
				 	}
			 		
			 		order_payment.push(order_payment_item);	

			 	   }
				}
			 })
			  
			 //如果剩下的充值卡不够支付
		 	if(remainNeedPay>0||noDiscountremainNeedPay>0){
		 		var zkcRate=-1;
		 		var rechargecard_id='';
				 $.each(rdate, function (i3, item3) {
					 //遍历充值卡
					 if(item3.rechargeCardCategory==2&&zkcRate==-1){
						 zkcRate=item3.discount_rate;
						 rechargecard_id=item3.rechargecard_id;
					 }					 
				 })		
				 
		 		var order_payment_item=new Object; 
		 		order_payment_item.payment_way_code=3;
		 		order_payment_item.payment_way='现金';
		 		order_payment_item.amount=remainNeedPay+noDiscountremainNeedPay;
		 		if(zkcRate!=-1){
		 			order_payment_item.totalAmount=(remainNeedPay)*zkcRate+noDiscountremainNeedPay;
		 			
		 			zhekou=zhekou+remainNeedPay*(1-zkcRate);
		 			
		 		}else{
		 			order_payment_item.totalAmount=remainNeedPay+noDiscountremainNeedPay;
		 		}
		 		
		 		order_payment_item.rechargecard_id=rechargecard_id;
		 		
		 		
		 		dzhRemainNeedPay=order_payment_item.totalAmount;
		 		order_payment.push(order_payment_item);	 		
		 	}
			 
			needToPay=needPay+noDiscountNeedPay;
			$('#needPay').html(needToPay);
			$('#totalAmount').html(sum);
			$('#remainNeedPay').html(remainNeedPay+noDiscountremainNeedPay);
			$('#dzhRemainNeedPay').html(dzhRemainNeedPay);
			//修改需要支付余额
			var rdate=$("#rechargeCard").data("kendoGrid").dataSource.data();
		};
		
	var checkOut = function(){
		var gridData = $("#grid").data("kendoGrid").dataSource.data();			 			 
        var phone=$("#phone").val();
		
		if(gridData.length<1){
			alert("请先输入商品");
			return false;
		}
		
		$("#total_amount").html("<span style='font-size:14px;color:red'>"+dzhRemainNeedPay+"</span>");		
		$("tr [name='tcontent']").remove();
	
		$.each(order_detail, function (i, item) {
			var tr = document.createElement("tr");
			var business_type_code = $("<td style='padding-left:15px;padding-top:2px' name='tcontent'/>");			
			$(business_type_code).html("<span style='font-size:14px'>"+item.business_type_code+"</span>");
			var unit = $("<td style='padding-left:15px;padding-top:2px' name='tcontent'/>");			
			$(unit).html("<span style='font-size:14px'>"+item.unit+"</span>");
			var itemAmount="";
			if(item.amount!=null){
				itemAmount=item.amount;
			}
			var amount = $("<td style='padding-left:15px;padding-top:2px' name='tcontent'/>");			
			$(amount).html("<span style='font-size:14px'>"+itemAmount+"</span>");
			
			var quantity = $("<td style='padding-left:15px;padding-top:2px' name='tcontent'/>");			
			$(quantity).html("<span style='font-size:14px'>"+item.quantity+"</span>");
			
			var pname = $("<td style='padding-left:15px;padding-top:2px' name='tcontent'/>");			
			$(pname).html("<span style='font-size:14px'>"+item.name+"</span>");
			
			var isUserCard='是';
			if(item.card_number==null){
				var isUserCard='否';
			}
			
			var isUserCardh = $("<td style='padding-left:15px;padding-top:2px' name='tcontent'/>");			
			$(isUserCardh).html("<span style='font-size:14px'>"+isUserCard+"</span>");
			$(tr).append(business_type_code);	
			$(tr).append(pname);
			$(tr).append(unit);
			$(tr).append(quantity);
			$(tr).append(amount);
			$(tr).append(isUserCardh);
					
			$("#order_detail").append(tr);
		})
		
		$.each(order_payment, function (i, item) {
			var tr = document.createElement("tr");
			var payment_way = $("<td style='padding-left:15px;padding-top:2px' name='tcontent'/>");			
			$(payment_way).html("<span style='font-size:14px'>"+item.payment_way+"</span>");
			
			var amount = $("<td style='padding-left:15px;padding-top:2px' name='tcontent'/>");			
			$(amount).html("<span style='font-size:14px'>"+item.totalAmount+"</span>");
			
			var itemcard_number="";
			if(item.card_number!=null){
				itemcard_number=item.card_number;
			}
	

			var card_number = $("<td style='padding-left:15px;padding-top:2px' name='tcontent'/>");			
			$(card_number).html("<span style='font-size:14px'>"+itemcard_number+"</span>");
			
			var totalAmount = $("<td style='padding-left:15px;padding-top:2px' name='tcontent'/>");			
			$(totalAmount).html("<span style='font-size:14px'>"+item.amount+"</span>");
	
			$(tr).append(payment_way);	
			$(tr).append(card_number);
			$(tr).append(amount);
			$(tr).append(totalAmount);
			
			$("#order_payment").append(tr);
			
		})
		
		$.fancybox($("#CheckContent"));
	}
		
	var submitContent = function(){
		var phone=$("#phone").val();
		var total_amount=needToPay+"";
		var payment_amount=needToPay+"";
		var desc='购买商品';
		var card_number=null;
		
		if(phone==''){
			phone=null;
		}

		var rechargeCardn=$("#rechargeCard").data("kendoGrid").dataSource.data();	
		
		
		if(cardList.length!=0){
			card_number= cardList[0].card_number;
		}else if(rechargeCardn.length!=0){
			card_number= rechargeCardn[0].card_number;
		}
		
		if(phone!=''&&card_number!=null){
			phone=null;
		}

		var kids_park_id='04428ed2-a555-11e5-8ece-1051721d3a6c';
		var order_detailp= JSON.stringify(order_detail);
		var order_paymentp= JSON.stringify(order_payment);
		
		var LODOP;
		
		  function myPrint(){
	        	LODOP=getLodop();         
		   		LODOP.PRINT_INIT("打印");	
		   		LODOP.SET_PRINT_PAGESIZE(3,580,40,"");	
				LODOP.ADD_PRINT_HTM(10,5,"100%","100%",document.getElementById("receipt").innerHTML);

 				if (LODOP.SET_PRINTER_INDEXA("GP-58130M Series")) {
				LODOP.PRINT();}
				else
					{
				alert("请准备好GP-58130M Series热敏打印机");
					}
	    	}
	        
		
		$.ajax( {  
            url:spera.spera_consume+"/consumeBackground/checkOut",// 跳转到 action  
            data: {
                     "phone" : phone,  
                     "total_amount" : total_amount,  
                     "payment_amount" : payment_amount,  
                     "desc" : desc  ,
                     "card_number":card_number,
                     "kids_park_id":kids_park_id,
                     "cashierID":cashierID,
                     "cashierName":cashierName,                   
                     "order_detail":order_detailp,
                     "order_payment":order_paymentp
					},  
//            type:'jsonp',  
            cache:false,  
            dataType:'jsonp',  
            success:function(data) {  
                if(data.status =="1" ){  
                    $("#receiptNumber").html(data.dataset.orderNumber);
					
                	var time = new Date().Format("yyyy-MM-dd hh:mm");
                	$("#receiptTime").html(time);
                    
					var totalitemList=new Array();
					
					//打印积分和余额
					if(data.dataset.card_out_number!=null){
											
						$("#dWxPoint").show();
						$("#wx_point").html(data.dataset.wx_point);		
						
						$("#dBalance").show();
						$("#balance").html(data.dataset.balance);	
						
						$("#dCardOutNumber").show();
						$("#cardOutNumber").html(data.dataset.card_out_number);						
					}						
                	var gdate=$("#grid").data("kendoGrid").dataSource.data();

        			 $.each(gdate, function (i, item) {
        				 var bool=true;
        				 
        				 $.each(totalitemList, function (i, itemt) {
            				 if(itemt.order_product_id==item.order_product_id){
            					 
            					 itemt.amount=itemt.amount+item.amount; 
            					 itemt.quantity=parseFloat(itemt.quantity)+parseFloat(item.quantity); 
            					 
            					 bool=false;      					            			
            				 }
            				 
            			 }) 
            			 if(bool==true){
            				 totalitemList.push(item);
            			 }
			 
            			 
        			 })
        			 
        			 $.each(totalitemList, function (i, item) {
        				 var tr=$("<tr></tr>") ;
        				 var td1=$("<td class='receiptth' style='width:160px'>"+item.name+"</td>") ;
        				 var td2=$("<td class='receiptth' style='width:60px'>"+item.quantity+"</td>") ;
        				 var td3=$("<td class='receiptth' style='width:60px'>"+item.amount+"</td>") ;
        				 
        				 $(tr).append(td1);
        				 $(tr).append(td2);
        				 $(tr).append(td3);
        				 
        				 $("#receiptItem").append(tr);      				 
        				 $("#receiptTotal").html(sum);
        				$("#zhekou").html(zhekou.toFixed(2));
        				$("#dikou").html(dikou.toFixed(2));
        				$("#receiptPaid").html((needPay+noDiscountNeedPay-zhekou).toFixed(2));

        			 })

        			 myPrint();
        			 myPrint();
        			 
        			 if(productNeedRegist.length!=0){
							var urlStr=basesperaUrl +koboo.login+'?orderID='+data.dataset.orderID; 
        					        $("#dialog").kendoWindow({
            	 						visible: true,
            	  						content: urlStr,
            	  						iframe: true,
            	  						actions: ["Minimize", "Maximize","Close" ],
            	  						height: "80%",
            	  						width:"80%",
            	  						position: {
            	  						    top: "10%", 
            	  						    left: "10%"
            	  						  },
            	  						close: function(e) {
            	  							window.location.reload();
            	  						}
            						});
            						var dialog = $("#dialog").data("kendoWindow");
        			 }
 			 
        			 //遍历cardList 循环打印消费
        				 
        				 var cardPayDatailList=new Array();     				 
        				 var gridData = $("#grid").data("kendoGrid").dataSource.data();	        				 
        				 var temp=false;
					
					$("#grid").data("kendoGrid").dataSource.data()

	      				 $.each(order_detail, function (i, gridcard) {
        					 if(gridcard.card_number!=null){
        						 cardPayDatailList.push(gridcard);
        						 temp=true;
        					 }
        				 })

		if(productNeedRegist.length==0){
			window.location.reload()
		}		
                if(temp==false){
               		
                }
                }else{  
                    alert(data.msg);  
                }  
             },  
             error : function() {  

                  alert("异常！");  
             }  
        });	
	};

var reload1= function(){
	window.location.reload();  
}

var  tcaddItem=function(selectItem){
	var selectItemarray=new Object();
	selectItemarray.name=selectItem.name;
	
	if(selectItem.promotion2.promotionTest==null||selectItem.promotion2.promotionTest==''){
		selectItemarray.unit_price=selectItem.unitPrice;
	}else{
		selectItemarray.unit_price=selectItem.promotion2.promotionTest;
	}
	
	selectItemarray.desc=selectItem.desc;
	selectItemarray.code=selectItem.code;
	selectItemarray.order_product_kids_park_id=selectItem.order_product_kids_prak_id;
	selectItemarray.quantity=selectItem.quantity;
	selectItemarray.isDiscount=selectItem.isDiscount;
	selectItemarray.isNeedRegistration=selectItem.isNeedRegistration;
	
	selectItemarray.order_product_id=selectItem.order_product_id;
	selectItemarray.business_type_code=selectItem.business_type_code;
	selectItemarray.unit_code=4;		
	selectItemarray.unit='元';		
	selectItemarray.amount=selectItemarray.quantity*selectItemarray.unit_price;
	selectItemarray.needpayquantity=selectItemarray.quantity;			
	selectItemarray.needpayamount=selectItemarray.quantity*selectItem.unitPrice;
	selectItemarray.member_card = {member_number:""}; 
	selectItemarray.remainQuantity=selectItem.remainQuantity;
	
	var griddata=$("#grid").data("kendoGrid").dataSource.data();
	
	var totalNumber=0;
	$.each(griddata, function (i, item) {
		if(item.order_product_kids_park_id==selectItemarray.order_product_kids_park_id)
			totalNumber=totalNumber+item.quantity;
	})
	totalNumber=totalNumber+selectItemarray.quantity;
	
	if(totalNumber>parseInt(selectItemarray.remainQuantity)){
		alert('库存不足');
		return false;
	}

	var cardContent=$("#cardContent").data("kendoGrid").dataSource.data();
	
	$.each(cardContent, function (i, item) {
		if(item.order_product_id==selectItem.order_product_id&&item.remain_quantity>=selectItem.quantity){
			selectItemarray.member_card ={member_number:item.member_number}; 
		}		
	})
	$("#grid").data("kendoGrid").dataSource.add(selectItemarray);	
	//初始化总金额
	totalAmount=0;
	//修改需要支付的总金额
	getTotalAmount();
}

